﻿//------------------------------------------------------------------------------------------------- 
// <copyright file="CreateWebApplication.cs" company="Collaboris Ltd.">
//   Copyright (c) Collaboris Ltd. All rights Reserved.
// </copyright>
// <summary>Creates a new SPWebApplication.</summary>
//-------------------------------------------------------------------------------------------------
namespace Collaboris.Saf.Actions.Wss.WebApplication
{
    using System;

    using Engine;

    using Entities;

    using Microsoft.SharePoint.Administration;

    using SharePoint.Wss.Attributes;
    using SharePoint.Wss.WebApplications;

    [CollaborisClass(
            Title = "Create Web Application",
            ReleaseStatus = ReleaseStatus.Stable,
            DisableDocumentation = false,
            ContactAuthorEmail = "Support@Collaboris.co.uk",
            Summary = "Creates a new SharePoint web application.",
            ClassGuid = "{156E17A5-A7BA-4e1f-8A48-1BC341A7C661}",
            UndoImplemented = true
        )
    ]
    public class CreateWebApplication : WSSActionBase<WebApplicationInfo>
    {

        /// <summary>
        /// Checks the Data entity used by the Action for Validity
        /// </summary>
        /// <param name="context">The <see cref="SafContext"/> passed in by the SAF Engine.</param>
        /// <param name="entity">The data entity to Validate.</param>
        /// <param name="errors">List of <see cref="ValidationError"/>s</param>
        /// <param name="mode"><see cref="ProcessMode"/>signalling wheter we are Doing, or Undoing the action.</param>
        /// <returns>false if invalid; otherwise true.</returns>
        protected override bool IsValid(
            SafContext context,
            WebApplicationInfo entity,
            ref System.Collections.Generic.List<ValidationError> errors,
            ProcessMode mode)
        {
            int currentCount = errors.Count;

            // Validate each object now.
            ValidateNullable(entity.Overwrite, "WebApplicationInfo.Overwrite", ref errors);

            if (!entity.CreateNewDatabase.HasValue)
                entity.CreateNewDatabase = false;
            
            if (!entity.DeleteContentDatabases.HasValue)
                entity.DeleteContentDatabases = false;

            if (!entity.Port.HasValue)
                entity.Port = 0;

            if (!entity.UseNTLM.HasValue)
                entity.UseNTLM = true;

            if (!entity.UseSSL.HasValue)
                entity.UseSSL = false;

            if (!entity.AllowAnonymous.HasValue)
                entity.AllowAnonymous = false;
            
            // Have we added errors ?
            return errors.Count == currentCount;

        }
        /// <summary>
        /// Undoes the action.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="entity">The entity.</param>
        /// <returns></returns>
        protected override ProcessStatus UndoAction(SafContext context, WebApplicationInfo entity)
        {
            string currentUrl = entity.Url;
            SPWebApplication webApplication = SPWebApplicationHelper.GetWebAppFromUrl(currentUrl);

            if (webApplication != null && entity.Overwrite.Value)
            {
                this.Trace.TraceVerbose("Deleting Existing Web Application : '{0}'", currentUrl);
                SPWebApplicationHelper.DeleteWebApplication(false, currentUrl);
                return ProcessStatus.Success;
            }

            return ProcessStatus.Skip;
        }

        /// <summary>
        /// This will create the web using the information as specified in the
        /// <see cref="WebApplicationInfo"/>
        /// </summary>
        /// <remarks>
        /// If you set the <see cref="WebApplicationInfo.Overwrite"/> to true and a Web App
        /// exists with a matching Url then it will be deleted and recreated.
        /// </remarks>
        /// <param name="context">The context.</param>
        /// <param name="entity">The data entityList.</param>
        /// <returns></returns>
        protected override ProcessStatus DoAction(SafContext context, WebApplicationInfo entity)
        {
            this.Trace.TraceMethodStart("DoAction");

            string currentUrl = entity.Url;

            // Can we get the Web App based on it's url ?
            SPWebApplication webApplication = SPWebApplicationHelper.GetWebAppFromUrl(currentUrl);

            if (webApplication != null && entity.Overwrite.Value)
            {
                this.Trace.TraceVerbose("Deleting Existing Web Application : '{0}'", currentUrl);
                SPWebApplicationHelper.DeleteWebApplication(entity.DeleteContentDatabases.Value, currentUrl);
            }

            if (webApplication != null && entity.Overwrite == false)
            {
                this.Trace.TraceError("Web Application : '{0}' exists nothing will be done.", entity.WebAppName);

                return ProcessStatus.Warning;
            }

            SPWebApplicationHelper.CreateWebApplication(
                    entity.Port.Value,
                    entity.AppPoolId,
                    entity.AppPoolUserName,
                    entity.AppPoolPassword,
                    entity.CreateNewDatabase.Value,
                    entity.DatabaseName,
                    entity.DatabaseServer,
                    entity.UseNTLM.Value,
                    entity.AllowAnonymous.Value,
                    entity.HostHeader,
                    entity.UseSSL.Value,
                    entity.RootDirectory,
                    entity.WebAppName);


            if (SPWebApplicationHelper.GetWebAppFromUrl(currentUrl) == null)
            {
                throw new ApplicationException(string.Format("This Web Application was not created : '{0}'", currentUrl));
            }

            this.Trace.TraceMethodEnd("DoAction");

            return ProcessStatus.Success;
        }
    }
 
}
